package com.springmvc.base;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.springmvc.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class ViewResolver {
    private Object modelAndView;
    private Handler handler;

    public ViewResolver(Object modelAndView,Handler handler) {
        this.modelAndView = modelAndView;
        this.handler = handler;
    }

    public void response(HttpServletRequest req,
                         HttpServletResponse resp) {
        try {
            if(modelAndView instanceof String){
                String viewName = (String) modelAndView;
                if(viewName.startsWith("redirect:")){
                    //重定向
                    String redirectPath = req.getContextPath() +"/"+ viewName.substring("redirect:".length());
                    resp.sendRedirect(redirectPath);
                }else{
                    //转发
                    String jspPath = "/WEB-INF/" + viewName + ".jsp";
                    req.getRequestDispatcher(jspPath).forward(req, resp);
                }
            }else {
                Method method = handler.getMethod();
                if (method.isAnnotationPresent(ResponseBody.class)) {
                    ObjectMapper mapper = new ObjectMapper();
                    String value = mapper.writeValueAsString(modelAndView);
                    resp.setContentType("text/html;charset=utf-8");
                    resp.getWriter().println(value);
                }
            }
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
